import { randomUUID } from "@/utils/index";
import { getFieldConfig } from "@/components/RuntimeComp";

const fieldConfig = getFieldConfig('Element')

export function isVue3Version(globalConfig) {
  return globalConfig?.codeVersion === "vue3" ?? false;
}

const keyPrefix = "formKey_";
const labelMap = {
  备注: "textarea",
  费: "input-number",
  状态: "select",
  类: "select",
  时间: "date-picker",
  日期: "date-picker",
};

export function fieldFactory(
  type,
  label,
  formKey,
  fieldList = [],
  required = false,
  smartType = true
) {
  let nType = type;
  smartType = typeof fieldList === "boolean" ? fieldList : smartType;
  if (smartType && label && !["groupForm", "subForm"].includes(type)) {
    for (const key of Object.keys(labelMap)) {
      if (label.endsWith(key)) {
        nType = labelMap[key];
      }
    }
  }
  if (["groupForm", "subForm"].includes(type)) {
    return {
      type: nType,
      label: label ?? "子表单_" + randomUUID(),
      formKey: formKey ?? keyPrefix + randomUUID(),
      props: {},
      fieldList: fieldList.map((item) =>
        fieldFactory("input", item.label, item.formKey, [], item.required)
      ),
      singleRow: true,
      layoutConfig: {
        // col: { span: 12 },
      },
      genConfig: {
        subFormType: "multiRow",
      },
    };
  } else {
    const f = {
      type: nType,
      label: label ?? "字段_" + randomUUID(),
      formKey: formKey ?? keyPrefix + randomUUID(),
      props: { ...(fieldConfig[type] ?? fieldConfig["input"]).props },
      rules: {},
    };
    if (required) {
      f.rules.required = true;
    }
    return f;
  }
}
